package com.jingjing.interceptor;

import com.jingjing.model.user.User;
import com.jingjing.service.user.LoginUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @program: jingjing
 * @description: 用户是否登录拦截
 * @author: 何伟
 * @create: 2019-03-19 12:05
 **/
@Component("LoginInterceptor")
public class LoginInterceptor implements HandlerInterceptor {

    Logger logger= LoggerFactory.getLogger(this.getClass());

    @Autowired
    LoginUserService loginUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String basePath = request.getContextPath();
        String path = request.getRequestURI();
        User user=null;
        //如果未登录了，跳转到登录页
        HttpSession session = request.getSession(false);
        if (null!=session) user =(User)session.getAttribute("user");

        if(null==session||user==null){
            logger.info("尚未登录或登录超时，跳转到登录界面");
            logger.info(basePath+path);
            response.sendRedirect(request.getContextPath()+"login");
            return false;
        }
        return true;
    }
}
